package pt.fct.mpc.lastfm.user;

import pt.fct.mpc.lastfm.MainActivity;
import pt.fct.mpc.lastfm.R;
import pt.fct.mpc.lastfm.album.AlbumActivity;
import pt.fct.mpc.lastfm.artist.ArtistActivity;
import pt.fct.mpc.lastfm.connectivity.bt.LastfmBluetoothManager;
import pt.fct.mpc.lastfm.database.LastfmDatabaseAdapter;
import pt.fct.mpc.lastfm.database.LastfmDatabaseFavourites;
import pt.fct.mpc.lastfm.database.LastfmDatabaseFavourites.FavouritesResult;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

public class LastfmFavouritesActivity
	extends Activity
{
	private static final String TAG = "Last.fm Favourites Activity";
	
	LastfmDatabaseFavourites favourites_db;
	LastfmDatabaseFavourites.FavouritesResult[] favourites;
	ArrayAdapter<String> favourites_array_adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.lastfm_favourites);

		
		this.favourites_db = 
			new LastfmDatabaseFavourites(this);
		
		this.favourites = this.favourites_db.getFavourites();
		
		if (favourites == null)
		{
			Log.e(TAG, "Favourites are returning null.");
			finish();
		}

		ListView favourites_lv = 
			(ListView) findViewById(R.id.layout_favourites_view_list);
		
		if (favourites.length == 0)
		{
			TextView favourites_no_results_view =
				(TextView) findViewById(R.id.layout_favourites_text_no_results);
			
			favourites_lv.setVisibility(View.GONE);
			favourites_no_results_view.setVisibility(View.VISIBLE);
			
			return;
		}
		
		favourites_array_adapter = new ArrayAdapter<String>(this, R.layout.list_item);
		
		
		registerForContextMenu(favourites_lv);
		favourites_lv.setAdapter(favourites_array_adapter);

		if (MainActivity.getInstance().hasAnyConnection() == true)
		{
			favourites_lv.setOnItemClickListener(
				new OnItemClickListener()
				{
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
						int position, long id)
					{
						FavouritesResult selected = favourites[position];

						String favourite_name = selected.getName();
						String favourite_type = selected.getType();

						String[] name_fields = favourite_name.split(":::");
						if (name_fields.length == 0)
						{
							Log.e(TAG, "Invalid favourite name: "+favourite_name);
							return;
						}

						jumpToGetInformations(name_fields, favourite_type);
					}

				});
		}

		populateArrayAdapter();
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		Log.d(TAG, "onPause()");
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		Log.d(TAG, "onResume()");
		
		if (this.favourites_array_adapter != null)
			populateArrayAdapter();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.favourites_options_menu, menu);
    	
    	return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
	   	boolean ret = true;
    	switch (item.getItemId())
    	{
    		case R.id.favourites_options_menu_remove_all:
    			favourites_db.removeAll();
    			
    			if (favourites_array_adapter != null)
    				favourites_array_adapter.clear();
    			break;
    	}
    	
    	return ret;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
		ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.favourites_context_menu, menu);
		
		boolean has_connectivity = 
			MainActivity.getInstance().hasAnyConnection();
		
		if (has_connectivity == false)
		{
			MenuItem infos_item = 
				menu.findItem(R.id.favourites_context_menu_get_infos);
			infos_item.setEnabled(false);
		}
		
		if (LastfmBluetoothManager.isOn() || (has_connectivity == false))
		{
			MenuItem share_item =
				menu.findItem(R.id.favourites_context_menu_share);
			
			share_item.setEnabled(false);
		}
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterContextMenuInfo info = 
			(AdapterContextMenuInfo) item.getMenuInfo();
		
		int list_position = (int) info.id;
		
		Log.d(getString(R.string.app_name), "list_position = "+list_position+
			", item id = "+item.getItemId());
		
		FavouritesResult entry = favourites[list_position];
		switch (item.getItemId())
		{
			case R.id.favourites_context_menu_get_infos:
				break;
			case R.id.favourites_context_menu_remove:
				if (entry == null)
				{
					Log.e(TAG, "Entry is null!");
					return false;
				}
				int entry_id = entry.getEntryID();
				boolean ret = favourites_db.removeEntry(entry_id);
				Log.d(TAG, "entry with ID "+entry_id+" remotion = "+ret);
				
				favourites = null;
				populateArrayAdapter();
				break;
				
			case R.id.favourites_context_menu_share:
				
				String share_subject = "Just added this to my favourites!";
				String share_text = "";
				
				String favourite_str = entry.toStringByType();
				int idx = favourite_str.indexOf('\n');
				
				if (idx < 0)
					share_text = "Artist: "+favourite_str;
				else
				{
					String artist = favourite_str.substring(0, idx);
					String album = favourite_str.substring(idx);
					
					share_text = album + ", " + artist;
				}
				
				Intent intent_action = new Intent(Intent.ACTION_SEND);
                intent_action.setType("text/plain");
                intent_action.putExtra(Intent.EXTRA_TEXT, share_text);
                intent_action.putExtra(Intent.EXTRA_SUBJECT, share_subject);
                intent_action.addCategory(Intent.CATEGORY_DEFAULT);
                Intent share = Intent.createChooser(intent_action, "Share");
                startActivity(share); 
                break;
		}
		
		return super.onContextItemSelected(item);
	}

	private void jumpToGetInformations(String[] name_fields, String type)
	{
		Bundle intent_data = new Bundle();
		Class<?> class_to_jump_to;
		
		if (type.equalsIgnoreCase(
			LastfmDatabaseAdapter.LASTFM_DATABASE_TYPE_ARTIST))
		{
			intent_data.putString("name", name_fields[0]);
			
			class_to_jump_to = ArtistActivity.class;
			
		} else if (type.equalsIgnoreCase(
			LastfmDatabaseAdapter.LASTFM_DATABASE_TYPE_ALBUM))
		{
			if (name_fields.length != 2)
			{
				Log.e(TAG, "Invalid number of fields for Album: "
					+"total fields = "+name_fields.length);
				return;
			}
			
			String album_name = name_fields[1];
			String artist_name = name_fields[0];
			intent_data.putString("name", album_name);
			intent_data.putString("artist", artist_name);
			
			class_to_jump_to = AlbumActivity.class;
			
		} else if (type.equalsIgnoreCase(
			LastfmDatabaseAdapter.LASTFM_DATABASE_TYPE_EVENT))
		{
			return;
		} else
		{
			Log.e(TAG, "Unrecognized type: "+type);
			return;
		}
		
		Intent intent = new Intent(this, class_to_jump_to);
		intent.putExtras(intent_data);
		startActivity(intent);
	}

	private void populateArrayAdapter()
	{
		if (favourites == null)
			favourites = favourites_db.getFavourites();
		
		favourites_array_adapter.clear();
		for (FavouritesResult r : favourites)
		{
			String str = r.toStringByType();
			if (str == null)
				continue;
			favourites_array_adapter.add(str);
		}		
	}

}
